package com.T4;

/**
 * @author GB
 * @data 2021/4/28 - 18:49
 * 解法2：使用归并算法
 * 但是归并的话时间和空间复杂度都是o(m+n)
 */
public class Solution4_2 {
    public static void main(String[] args) {
        int[] nums1 = new int[]{5,9};
        int[] nums2 = new int[]{2,  3};

        Solution4_2 S4 = new Solution4_2();

        double result = S4.findMedianSortedArrays(nums1, nums2);
        System.out.println("结果是：" + result);
    }

    private static int[] merge(int[] a,int[] b){
        int[] temp=new int[a.length+b.length];
        int i=0;
        int j=0;
        int k=0;
        while (i<a.length && j<b.length){
            temp[k++]=a[i]<b[j]?a[i++]:b[j++];
        }
        while (i<a.length){
            temp[k++]=a[i++];
        }
        while (j<b.length){
            temp[k++]=b[j++];
        }
        return temp;
    }

    public double findMedianSortedArrays(int[] nums1,int[] nums2){
        int[] c=merge(nums1,nums2);
        return c.length%2==1?c[c.length/2]:((double) c[c.length/2]+c[c.length/2-1])/2;
    }
}
